package com.macro.mall.tiny.modules.pms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.api.ResultCode;
import com.macro.mall.tiny.modules.pms.model.PmsElectricMasterData;
import com.macro.mall.tiny.modules.pms.model.PmsErrorCode;
import com.macro.mall.tiny.modules.pms.service.PmsElectricMasterDataService;
import com.macro.mall.tiny.modules.pms.service.PmsUserActionService;
import com.macro.mall.tiny.modules.ums.model.UmsMember;
import com.macro.mall.tiny.security.util.MemberContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tyrone
 * @since 2024-10-28
 */
@RestController
@RequestMapping("/pms/pmsElectricMasterData")
@Api(tags = "PmsElectricMasterDataController")
@Tag(name = "PmsElectricMasterDataController", description = "电工大师数据管理")
public class PmsElectricMasterDataController {

    @Autowired
    private PmsElectricMasterDataService pmsElectricMasterDataService;
    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation("获取三大类型及其子类")
    @GetMapping("getCategoryAndItem")
    public CommonResult<PmsElectricMasterDataHomePageVO> getCategoryAndItem() {
        List<PmsElectricMasterData> mainCategory = pmsElectricMasterDataService.query().eq("parent_id", 0).list();
        Map<String, PmsElectricMasterData> mainMap = mainCategory.stream().collect(Collectors.toMap(PmsElectricMasterData::getName, e -> e));
        List<PmsElectricMasterData> categoryList = pmsElectricMasterDataService.query().in("parent_id", mainCategory.stream().map(PmsElectricMasterData::getId).toArray()).list();
        Map<Integer, List<PmsElectricMasterData>> collect =
                categoryList.stream().collect(Collectors.groupingBy(PmsElectricMasterData::getParentId));
        PmsElectricMasterDataHomePageVO pmsElectricMasterDataHomePageVO = new PmsElectricMasterDataHomePageVO();
        pmsElectricMasterDataHomePageVO.setBasicCategoryList(collect.get(mainMap.get("电工基础").getId()));
        pmsElectricMasterDataHomePageVO.setPartmentCategoryList(collect.get(mainMap.get("电气部件").getId()));
        pmsElectricMasterDataHomePageVO.setGraphCategoryList(collect.get(mainMap.get("电路图册").getId()));
        return CommonResult.success(pmsElectricMasterDataHomePageVO);
    }

    @ApiOperation("前台增加浏览量")
    @GetMapping("addViewNum")
    public CommonResult<Void> addViewNum(@ApiParam("数据类型") @RequestParam Integer type, @ApiParam("数据id") @RequestParam String name) {
        pmsElectricMasterDataService.update()
                .setSql("view_num = view_num + 1").eq("type", type).eq("name", name).update();
        return CommonResult.success(null);
    }

    @ApiOperation("前台搜索接口")
    @GetMapping("/search")
    public CommonResult<List<PmsElectricMasterData>> search(@ApiParam("搜索关键字") @RequestParam(required = false) String keyword,
                                                            @RequestParam(required = false) Integer id
    ) {
        QueryChainWrapper<PmsElectricMasterData> query = pmsElectricMasterDataService.query();
        UmsMember member = MemberContext.getMember();
        if (member != null) {
            String key = "PmsElectricMasterData:" + member.getId();
            // 删除重复记录
            redisTemplate.opsForList().remove(key, 0, keyword);
            // 添加到列表头部
            redisTemplate.opsForList().leftPush(key, keyword);
            // 限制列表长度
            redisTemplate.opsForList().trim(key, 0, 9);

        }
        if (keyword == null && id == null) {
            return CommonResult.failed(ResultCode.VALIDATE_FAILED);
        }
        query.ne("type", 0).ne("type", 1);
        if (StringUtils.isNotEmpty(keyword)) {
            query.like("name", keyword);
        }
        if (id != null) {
            query.eq("id", id);
        }
        query.orderByAsc("type");
        List<PmsElectricMasterData> list = query.list();
        handlePrivacyData(list);
        return CommonResult.success(list);
    }


    @ApiOperation("获取子类")
    @GetMapping("getSubItem")
    public CommonResult<PmsElectricMasterDataVO> getCategoryAndItem(@ApiParam("当前分类id") @RequestParam Integer id,
                                                                    @ApiParam("排序类型 0创建时间 1浏览量 2收藏量") @RequestParam(required = false) Integer sortType) {
        QueryChainWrapper<PmsElectricMasterData> query = pmsElectricMasterDataService.query().eq("parent_id", id);

        List<PmsElectricMasterData> list = query.list();
        List<PmsElectricMasterData> directoryList = list.stream().filter(e -> e.getType() == 1).collect(Collectors.toList());
        List<PmsElectricMasterData> fileList = list.stream().filter(e -> e.getType() != 1).collect(Collectors.toList());
        if (!fileList.isEmpty()) {
            if (sortType == null || sortType == 0) {
                fileList.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));
            } else if (sortType == 1) {
                fileList.sort((a, b) -> b.getViewNum().compareTo(a.getViewNum()));
            } else if (sortType == 2) {
                fileList.sort((a, b) -> b.getCollectNum().compareTo(a.getCollectNum()));
            }
        }
        handlePrivacyData(directoryList);
        handlePrivacyData(fileList);
        PmsElectricMasterDataVO vo = new PmsElectricMasterDataVO();
        vo.setDirectoryList(directoryList);
        vo.setFileList(fileList);
        return CommonResult.success(vo);
    }

    @ApiOperation("后台万能分页查询接口 支持id parentId type name showStatus 字段查询 按照创建时间倒序输出")
    @PostMapping("page")
    public CommonResult<IPage<PmsElectricMasterData>> page(@RequestBody PmsElectricMasterData pmsElectricMasterData) {
        QueryWrapper<PmsElectricMasterData> query = new QueryWrapper<>();
        if (pmsElectricMasterData.getId() != null) query.eq("id", pmsElectricMasterData.getId());
        if (pmsElectricMasterData.getParentId() != null) query.eq("parent_id", pmsElectricMasterData.getParentId());
        if (pmsElectricMasterData.getType() != null) query.eq("type", pmsElectricMasterData.getType());
        if (StringUtils.isNotEmpty(pmsElectricMasterData.getName()))
            query.like("name", pmsElectricMasterData.getName());
        if (pmsElectricMasterData.getShowStatus() != null)
            query.eq("show_status", pmsElectricMasterData.getShowStatus());
        query.orderByDesc("create_time");
        return CommonResult.success(pmsElectricMasterDataService.page(new Page<>(pmsElectricMasterData.getPageNum(), pmsElectricMasterData.getPageSize(), true), query));
    }

    @ApiOperation("后台更新接口")
    @PostMapping("update")
    public CommonResult<Boolean> update(@RequestBody PmsElectricMasterData pmsElectricMasterData) {
        return CommonResult.success(pmsElectricMasterDataService.updateById(pmsElectricMasterData));
    }

    @ApiOperation("后台添加接口")
    @PostMapping("add")
    public CommonResult<Boolean> add(@RequestBody PmsElectricMasterData pmsElectricMasterData) {
        return CommonResult.success(pmsElectricMasterDataService.save(pmsElectricMasterData));
    }

    @ApiOperation("后台删除接口")
    @PostMapping("delete")
    public CommonResult<Boolean> delete(@RequestBody List<Integer> ids) {
        return CommonResult.success(pmsElectricMasterDataService.removeByIds(ids));
    }

    @ApiOperation("后台获取树形分类")
    @GetMapping("getTreeCategory")
    public CommonResult<List<PmsElectricMasterData>> getTreeCategory() {
        List<PmsElectricMasterData> list = pmsElectricMasterDataService.query().eq("type", 0).or().eq("type", 1).list();
        Map<Integer, PmsElectricMasterData> electricMasterDataMap = list.stream().collect(Collectors.toMap(PmsElectricMasterData::getId, e -> e));
        List<PmsElectricMasterData> treeData = list.stream().filter(e -> e.getParentId() == 0).collect(Collectors.toList());
        List<PmsElectricMasterData> needMerge = list.stream().filter(e -> e.getParentId() != 0).collect(Collectors.toList());
        for (PmsElectricMasterData pmsElectricMasterData : needMerge) {
            PmsElectricMasterData parent = electricMasterDataMap.get(pmsElectricMasterData.getParentId());
            if (parent != null) {
                if (parent.getChildren() == null) {
                    parent.setChildren(Lists.newArrayList(pmsElectricMasterData));
                } else {
                    parent.getChildren().add(pmsElectricMasterData);
                }
            }
        }
        return CommonResult.success(treeData);


    }


    @Data
    public class PmsElectricMasterDataHomePageVO {
        @ApiModelProperty("电工基础")
        private List<PmsElectricMasterData> basicCategoryList;

        @ApiModelProperty("电气部件")
        private List<PmsElectricMasterData> partmentCategoryList;

        @ApiModelProperty("电路图册")
        private List<PmsElectricMasterData> graphCategoryList;
    }

    @Autowired
    private PmsUserActionService pmsUserActionService;

    private void handlePrivacyData(List<PmsElectricMasterData> lists) {
        if (MemberContext.getMember() != null) {
            List<Object> objects = pmsUserActionService.listItem(2, 1);
            for (PmsElectricMasterData data : lists) {
                if (objects.contains(data.getId())) {
                    data.setCurrentMemberCollect(1);
                } else {
                    data.setCurrentMemberCollect(0);
                }
            }
        }
    }

    @Data
    public class PmsElectricMasterDataVO {
        @ApiModelProperty("文件夹类型")
        private List<PmsElectricMasterData> directoryList;

        @ApiModelProperty("文件类型")
        private List<PmsElectricMasterData> fileList;
    }


}

